﻿namespace Digitalmes.Application.Sys.Roles.Commands;

/// <summary>
/// 给角色授权菜单命令。
/// </summary>
public record GrantMenusCommand(long RoleId, long[] MenuIds) : IRequest<IResult<bool>>;

internal sealed class GrantMenusCommandHandler(IRepository<SysRoleMenu> repo) : IRequestHandler<GrantMenusCommand, IResult<bool>>
{
    public async Task<IResult<bool>> Handle(GrantMenusCommand request, CancellationToken cancellationToken)
    {
        List<SysRoleMenu> roleMenus = request.MenuIds
            .Distinct()
            .Select(menuId => new SysRoleMenu
            {
                RoleId = request.RoleId,
                MenuId = menuId,
            }).ToList();

        // 删除原有的映射关系
        await repo.DeleteAsync(m => m.RoleId == request.RoleId, cancellationToken);

        if (roleMenus.Count == 0)
        {
            return Result.Success();
        }

        // 添加新的映射关系
        var result = await repo.InsertRangeAsync(roleMenus, cancellationToken);

        return Result.From(result);
    }
}
